package org.anachronos.jeep.ui.attach;

import org.anachronos.jeep.core.attach.VirtualMachineAttachement;
import org.anachronos.jeep.core.attach.VirtualMachineRemoteControl;
import org.anachronos.jeep.core.attach.VirtualMachineAttachement.State;
import org.anachronos.jeep.ui.JeepUiPlugin;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.jface.window.Window;
import org.eclipse.jface.wizard.WizardDialog;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.handlers.HandlerUtil;

public class AttachCommand extends VirtualMachineAttachementCommand {
	
	@Override
	public Object execute(final ExecutionEvent event) throws ExecutionException {
		final IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindow(event);
		final VirtualMachineAttachement vmToAttach = getSelection(event);
		final NewAttachmentWizard wizard = new NewAttachmentWizard();
		final WizardDialog wizardDialog = new WizardDialog(window.getShell(), wizard);
		final int openResult = wizardDialog.open();
		if (openResult == Window.OK) {
			final String configFile = wizard.getConfigFile();
			final VirtualMachineRemoteControl virtualMachineRemoteControl = 
				JeepUiPlugin.getDefault().getVirtualMachineRemoteControl();
			try {
				final VirtualMachineAttachement attachedVm = 
					virtualMachineRemoteControl.attach(vmToAttach, configFile);
				vmToAttach.setState(State.ATTACHED);
				vmToAttach.setJmxServiceURL(attachedVm.getJmxServiceURL());
			} catch (final Exception e) {
				throw new ExecutionException("Attaching profiler failed!", e);
			}
		}
		return null;
	}
}
